FROM daocloud.io/lamozarax/ubuntu-boostrap:master-f75fc62
MAINTAINER lamozarax dev@xiaogu-tech.com

ENV SITENAME=lamozarax-lms.daoapp.io
ARG SITENAME=lamozarax-lms.daoapp.io

RUN locale-gen en_US en_US.UTF-8
ENV LC_ALL="en_US.UTF-8"

RUN mkdir -p /root/.ssh/
COPY ./deploy/id_rsa /root/.ssh/id_rsa
RUN chmod 400 /root/.ssh/id_rsa
RUN touch /root/.ssh/known_hosts
RUN ssh-keyscan github.com >> /root/.ssh/known_hosts

RUN git clone git@github.com:laioffer-inc/LMS.git /sites/$SITENAME/
RUN pip install -r /sites/$SITENAME/deploy_tools/requirements/staging.txt

ARG CACHE_DATE

# DB related start
USER postgres
RUN    /etc/init.d/postgresql start &&\
    psql --command "CREATE DATABASE lms;" &&\
    psql --command "CREATE USER lmsuser WITH PASSWORD 'password';" &&\
    psql --command "ALTER ROLE lmsuser SET client_encoding TO 'utf8';" &&\
    psql --command "ALTER ROLE lmsuser SET default_transaction_isolation TO 'read committed';" &&\
    psql --command "ALTER ROLE lmsuser SET timezone TO 'UTC';" &&\
    psql --command "GRANT ALL PRIVILEGES ON DATABASE lms TO lmsuser;"

RUN echo "listen_addresses='*'" >> /etc/postgresql/9.5/main/postgresql.conf
USER root
RUN /etc/init.d/postgresql restart

ENV DJANGO_SETTINGS_MODULE=config.settings_staging
ENV LMS_DB_HOST=localhost
ENV LMS_DB_PORT=
ENV LMS_DB_NAME=lms
ENV LMS_DB_USER=lmsuser
ENV LMS_DB_PWD=password

COPY ./deploy/cleanup.sh /sites/$SITENAME/misc/cleanup.sh
RUN sh /sites/$SITENAME/misc/cleanup.sh
# DB related end

WORKDIR /sites/$SITENAME
RUN git pull origin master

WORKDIR /sites/$SITENAME/source
RUN gunicorn --bind unix:/tmp/$SITENAME.socket --daemon config.wsgi:application

# nginx related
COPY ./deploy/nginx.conf /etc/nginx/sites-available/lms.conf
RUN mv "/etc/nginx/sites-available/lms.conf" "/etc/nginx/sites-available/$SITENAME"
RUN sed -i "s/SITENAME/$SITENAME/g" "/etc/nginx/sites-available/$SITENAME"
RUN ln -s "/etc/nginx/sites-available/$SITENAME" "/etc/nginx/sites-enabled/$SITENAME"
RUN rm /etc/nginx/sites-enabled/default
RUN python manage.py collectstatic --noinput
# nginx related end

EXPOSE 80
CMD ["nginx", "-g", "daemon off;"]